package edu.ynu.MyProject.config;

import edu.ynu.MyProject.shiro.JpaRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean(name = "shiroJpaRealm")
    public JpaRealm jpaRealm() {
        JpaRealm realm = new JpaRealm();

        // 配置密码匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5"); // 设置加密算法为 MD5
        matcher.setHashIterations(1);       // 设置加密迭代次数（与注册加密一致）
        realm.setCredentialsMatcher(matcher);

        return realm;
    }

    @Bean
    public SecurityManager securityManager(@Qualifier("shiroJpaRealm") JpaRealm jpaRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(jpaRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        // 配置拦截规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 开放的接口

        // 需要认证的接口
//        filterChainDefinitionMap.put("/**", "authc"); // 其他接口需要认证
        filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return filterFactoryBean;
    }
}
